package com.example.springboottest.dynamicprocess;

import org.apache.commons.io.IOUtils;

import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * 可以执行所有机器上的command命令
 * <p>
 * 以此类推，可以通过字节码得到类，再反射执行
 */
public class DynamicCommand {
    public static void main(String[] args) throws Exception {
        /*动态执行command命令,ifconfig;ls;pwd
          等同于Runtime.getRuntime().exec("command命令");
         */
        String command = "pwd";
        dynamicExecCommand(command);
        byte[] bytes = new byte[1024];
        Runtime.getRuntime().exec("date").getOutputStream();
        String result = new String(bytes);
        System.out.println(result);
    }


    public static void dynamicExecCommand(String command) throws Exception {
        String string = "java.lang.Runtime";
        byte[] classBytes = string.getBytes();
        System.out.println(string + "类的字节码\t" + Arrays.toString(classBytes));

        //byte[] classBytes = [106, 97, 118, 97, 46, 108, 97, 110, 103, 46, 82, 117, 110, 116, 105, 109, 101]
        String run = new String(classBytes);
        Class runtimeClass = Class.forName(run);
        Constructor declaredConstructor = runtimeClass.getDeclaredConstructor();
        declaredConstructor.setAccessible(true);
        Object o = declaredConstructor.newInstance();
        Method exec = runtimeClass.getMethod("exec", String.class);
        //等同于
//        Runtime.getRuntime().exec(command);


        Process process = (Process) exec.invoke(o, command);
        InputStream inputStream = process.getInputStream();    //获取输出的数据

        String result = IOUtils.toString(inputStream, "gbk"); //字节输出流转换为字符
        System.out.println(result);
    }
}